import React, { useState, useEffect, useMemo, useCallback } from 'react'
import { Button, MessagePlugin } from 'tdesign-react';
import { Outlet, useNavigate, useLocation, Link, useSearchParams } from 'react-router-dom';
import { Topic, RadioCount, OptionCount, JudgmentCount, ShortCount, Clazz, AddExam, Paper } from '../../../axiosAPI/lzh'

const ExamAdd = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();
  const location = useLocation();
  const [topic, setTopic] = useState(
    {
      radio: {
        range: [],
        judgment: 0,
        fraction: '',
        num: '',
      }, options: {
        range: [],
        judgment: 0,
        fraction: '',
        num: ''
      }, judgment: {
        range: [],
        judgment: 0,
        fraction: '',
        num: ''
      }, short: {
        range: [],
        judgment: 0,
        fraction: '',
        num: ''
      }
    }
  )
  const _id = localStorage.getItem('_id') || '66d01b681c9b3a7e402cc853'
  const [radioNum, setradioNum] = useState(0)
  const [optionsNum, setoptionsNum] = useState(0)
  const [judgmentNum, setjudgmentNum] = useState(0)
  const [shortNum, setshortNum] = useState(0)
  const [options, setoptions] = useState([])
  const [questions, setquestions] = useState([])
  const [SelectedRowKeys, setSelectedRowKeys] = useState([]);
  const [data, setData] = useState([])
  const [totalTopicLength, setTotalTopicLength] = useState(0)
  const [score, setScore] = useState('')
  const [pagesize, setpagesize] = useState(2);
  const [page, setpage] = useState(1);
  const [tree, setTree] = useState([])
  const [type,settype] = useState(true)
  const [updateId, setupdateId] = useState('')
  const [exam, setExam] = useState({
    name: '',
    time: [],
    pass_score: '',
    out: '',
    creator: localStorage.getItem('_id') || '66d4723de40bcbb6f5a6bcf0',
    questions: [],
    type: null,
    belong: '',
    class: [],
    flag:1,
    publishTime: Date.now(),
  })
  const handleExamUpdate = (obj) => {
    setExam({ ...exam, ...obj })
  }

  const data1 = useMemo(() => {
    return data.map(item => {
      if (data.length === 0) {
        return data
      } else {
        return { ...item, score }
      }
    })
  }, [score, data])
  useEffect(() => {
    if (searchParams.get('_id')) {
      setupdateId(searchParams.get('_id'))
      getPaper();
      if(topic.radio.range){
        console.log(topic.radio.range);
      }
      getradioLength();
      getoptionLength();
      getshortLength();
      getjudgementLength();
      console.log(exam,'0--------------');
    }
    getTree()
  }, [_id])
  useEffect(()=>{
    getTopic();
  },[page,pagesize])
  const getPaper = async () => {
    const { data: { code, obj, exam,length,questions,average } } = await Paper({ _id: searchParams.get('_id') })
    setExam(exam)
    // console.log(exam,'exam----------');
    setTopic(obj);
    setradioNum(length.radio);
    setoptionsNum(length.options);
    setshortNum(length.short);
    setjudgmentNum(length.judgment);
    setScore(average);
    if(questions.length!==0){
      // console.log(questions,typeof questions,'1---------------');
      setSelectedRowKeys(questions)
    }
  }
  const handleChange1 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      radio: {
        ...prevTopic.radio,
        range: v
      }
    }));
  }
  const handleChange5 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      options: {
        ...prevTopic.options,
        range: v
      }
    }));
  }
  const handleChange9 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      judgment: {
        ...prevTopic.judgment,
        range: v
      }
    }));
  }
  const handleChange13 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      short: {
        ...prevTopic.short,
        range: v
      }
    }));
  }
  const handleChange2 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      radio: {
        ...prevTopic.radio,
        judgment: v
      }
    }));
  }
  const handleChange6 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      options: {
        ...prevTopic.options,
        judgment: v
      }
    }));
  }
  const handleChange10 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      judgment: {
        ...prevTopic.judgment,
        judgment: v
      }
    }));
  }
  const handleChange14 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      short: {
        ...prevTopic.short,
        judgment: v
      }
    }));
  }

  const handleChange3 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      radio: {
        ...prevTopic.radio,
        num: v
      }
    }));
  }
  const handleChange7 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      options: {
        ...prevTopic.options,
        num: v
      }
    }));
  }
  const handleChange11 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      judgment: {
        ...prevTopic.judgment,
        num: v
      }
    }));
  }
  const handleChange15 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      short: {
        ...prevTopic.short,
        num: v
      }
    }));
  }

  const handleChange4 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      radio: {
        ...prevTopic.radio,
        fraction: v
      }
    }));
  }
  const handleChange8 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      options: {
        ...prevTopic.options,
        fraction: v
      }
    }));
  }
  const handleChange12 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      judgment: {
        ...prevTopic.judgment,
        fraction: v
      }
    }));
  }
  const handleChange16 = (v) => {
    setTopic(prevTopic => ({
      ...prevTopic,
      short: {
        ...prevTopic.short,
        fraction: v
      }
    }));
  }
  const getTopic = async () => {
    const { data: { code, arr, questions,total } } = await Topic({ page, pagesize, _id })
    if (code === 200) {
      setoptions(arr)
      setquestions(questions)
      setTotalTopicLength(total)
    }
  }
  const getTree = async () => {
    const { data: { code, tree } } = await Clazz()
    if (code === 200) {
      setTree(tree)
    } else {
      MessagePlugin.error('获取班级失败')
    }
  }

  const getradioLength = async () => {
    const { data: { code, length } } = await RadioCount({ radio: topic.radio.range })
    setradioNum(length)
  }

  const getoptionLength = async () => {
    const { data: { code, length } } = await OptionCount({ options: topic.options.range })
    setoptionsNum(length)
  }

  const getjudgementLength = async () => {
    const { data: { code, length } } = await JudgmentCount({ judgment: topic.judgment.range })
    setjudgmentNum(length)
  }

  const getshortLength = async () => {
    const { data: { code, length } } = await ShortCount({ short: topic.short.range })
    setshortNum(length)
  }
  const Sumbit = async () => {
      if(!exam.type&&!topic.radio.fraction) {
        MessagePlugin.error('请设置题目分值')
        return
      }
    
    const { data: { code } } = await AddExam({ exam, topic, data,_id:updateId })
    if (code === 200) {
      MessagePlugin.success('提交成功')
      navigate(-1)
      // setExam({
      //   name:'',
      //   time:[],
      //   pass_score:'',
      //   out:'',
      //   creator:localStorage.getItem('_id') || '66d01b681c9b3a7e402cc853',
      //   questions:[],
      //   type:true,
      //   belong:'',
      //   class:[],
      //   publishTime:Date.now(),
      // })
      // setSelectedRowKeys([]);
      // setTopic({
      //   radio: {
      //     range: [],
      //     judgment: 0,
      //     fraction: '',
      //     num: '',
      //   }, options: {
      //     range: [],
      //     judgment: 0,
      //     fraction: '',
      //     num: ''
      //   }, judgment: {
      //     range: [],
      //     judgment: 0,
      //     fraction: '',
      //     num: ''
      //   }, short: {
      //     range: [],
      //     judgment: 0,
      //     fraction: '',
      //     num: ''
      //   }
      // })
    } else {
      MessagePlugin.error('提交失败')
    }
  }
  return (
    <div id='examAdd'>
      <div className="tab">
        <div className='as'>
          <Link to={!updateId?`/home/examAdd/topic`:`/home/examAdd/topic?_id=${updateId}`} className={location.pathname === '/home/examAdd/topic' ? 'acttab' : ''}>题目配置</Link>
          <Link to={!updateId?`/home/examAdd/setting`:`/home/examAdd/setting?_id=${updateId}`} className={location.pathname === '/home/examAdd/setting' ? 'acttab' : ''}>考试配置</Link>
        </div>
        <div className='btn'>
          <Button onClick={() => navigate(!updateId?`/home/examAdd/setting`:`/home/examAdd/setting?_id=${updateId}`)}>下一步</Button>
          <Button onClick={() => navigate(-1)}>返回</Button>
        </div>
      </div>
      <Outlet context={{
        Sumbit, tree, getshortLength, getjudgementLength, getoptionLength, getradioLength,
        options, page, pagesize, setpage, setpagesize, getTopic, score, setScore, data1, setData,
        SelectedRowKeys, setSelectedRowKeys, questions, radioNum, optionsNum,
        judgmentNum, shortNum, exam, handleExamUpdate, topic, handleChange1,
        handleChange2, handleChange3, handleChange4, handleChange5, handleChange6,
        handleChange7, handleChange8, handleChange9, handleChange10, handleChange11,
        handleChange12, handleChange13, handleChange14, handleChange15, handleChange16,
        totalTopicLength
      }} />
    </div>
  )
}

export default ExamAdd
